import traceback
from datetime import datetime

from mg_app_framework import HttpClient, get_logger
from tornado.simple_httpclient import HTTPTimeoutError

from common_bind_service.utils.db import get_workorder_record


class FMSDataService:
    authorization_token = 'QTZENzVFMzA2NDAwN0I1RTQwNUM4QTM4NEY1RUQ0QzUyRjY1Q0FFNDgwNTYzQ0ZENDY1MzdCQjUzNDczNzAyMjg3NTJCRkEzMUZENjI3QjE4QUQzQzIzRTFENzM5MjZD'

    @classmethod
    async def fetch_fms_data(cls, fms_url, fms_post_data):
        try:
            headers = {'content-type': 'application/json',
                       'authorization': f'Bearer {cls.authorization_token}'}
            fetch = await HttpClient().post(fms_url, fms_post_data, headers=headers)
            fetch_data = fetch.body
            if fetch_data['code'] != 200:
                status = fetch_data.get('status')
                data = fetch_data.get('data')
                return None, f'FMS接口返回失败:{status}:{data}'
        except HTTPTimeoutError as e:
            return None, 'FMS空托盘接口调用超时'
        except Exception as e:
            get_logger().error(f'fms调用错误,{traceback.format_exc()}')
            return None, 'FMS空托盘接口调用失败'
        return fetch_data, ''

    @classmethod
    async def handle_process_post_data(cls, param):
        cells = []
        for cell_sn in param.cell_list:
            cells.append({
                'cellBarCode': cell_sn.cell_sn,
                'channel': cell_sn.slot_no,
                'cellState': 100,  # 电芯状态，固定传100
            })
        now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        work_order_record_db = get_workorder_record()
        work_order = await work_order_record_db.find_one(
            {'procedure_code': param.process_code, 'workorder_status': 'on_work'})
        process_code_trans_map = {
            'C140': 'C150',
            'C160': 'C170',
            'C220': 'C230-2',
        }
        fms_process_code = process_code_trans_map.get(param.process_code, '')

        in_data = {
            'lotNo': work_order['batch_number'],  # 批次号
            'cellType': work_order['specification_model'],  # 电芯类型
            'processCode': fms_process_code,  # 工序编码
            'lineNo': 'A',  # 线体，固定为单字符 A
            'trayNo': param.vehicle_no,  # 托盘码
        }
        fms_post_data = {'data': {}}
        if fms_process_code == 'C150':  # 一次注液工序
            cells = [{**i, **{'lotAttr2': now_str}} for i in cells]
            in_data.update(
                {
                    'deviceNo': param.equip_code,  # 设备编码
                    'cells': cells,  # 电芯列表
                }
            )
            fms_post_data['data'] = in_data
            fms_post_data['resourceNo'] = 'FMS_WMS_TRAY_CELL'
        elif fms_process_code in ['C170', 'C230-2']:  # [二次注液工序,包膜工序]
            if fms_process_code == 'C170':
                cells = [{**i, **{'lotAttr3': now_str}} for i in cells]
            else:
                cells = [{**i, **{'lotAttr4': now_str}} for i in cells]
            in_data.update(
                {
                    'cells': cells,  # 电芯列表
                }
            )
            fms_post_data['data'] = in_data
            fms_post_data['resourceNo'] = 'FMS_CYC_REBIND_CELL_TO_TRAY'

        else:
            return {}, '工序编码传入错误，取消调用fms'
        return fms_post_data, ''
